'''
Created on 2014. 3. 11.

@author: '
'''
####################################################
# library import and object instance.              #
####################################################
# import
import os
import sys
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
sys.path.append('D:\\_workspace\\_python_workspace\\nlib')
from Nlog import Nlog

####################################################
# application configration                         #
####################################################
app = Flask(__name__)
DATABASE = 'D:\_workspace\_python_workspace\flaskCRUDExample\flask_crud.db'
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flask_crud.db'),
    DEBUG=True,
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

nlog = Nlog();
nlog.puts('test');

####################################################
# method                                           #
####################################################
def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema_sqlite.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

def get_db():
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

####################################################
# route                                            #
####################################################
@app.route('/')
def list():
    db = get_db()
    cur = db.execute('select id, title, contents from entries order by id desc')
    entries = cur.fetchall()
    template = render_template('list.html', entries=entries)
    return template

@app.route('/create')
def create():
    template = render_template('create.html')
    return template

@app.route('/create', methods=['POST'])
def create_proc():
    db = get_db()
    db.execute('insert into entries (title, contents) values (?, ?)', [request.form['title'], request.form['contents']])
    db.commit()
    flash('New entry was successfully posted')
    template = redirect(url_for('list'))
    return template

@app.route('/retrieve/<int:id>')
def retrieve(id):
    entry = get_db().execute('select * from entries where id="%s"' % id).fetchone()
    template = render_template('retrieve.html', entry=entry, id=id)
    return template

@app.route('/update/<int:id>')
def update(id):
    entry = get_db().execute('select * from entries where id="%s"' % id).fetchone()
    template = render_template('update.html', entry=entry, id=id)
    return template

@app.route('/update', methods=['POST'])
def update_proc():
    db = get_db()
    db.execute('update entries set title=(?), contents=(?) where id=(?)', [request.form['title'], request.form['contents'], request.form['id']])
    db.commit()
    template = redirect(url_for('retrieve', id=request.form['id']))
    return template

@app.route('/delete/<int:id>')
def delete(id):
    db = get_db()
    db.execute('delete from entries where id="%s"' % id)
    db.commit()
    template = render_template('delete.html', id=id)
    return template


####################################################
# and here we go                                    #
####################################################\
if __name__ == '__main__':
    init_db()
    app.run(debug=True)